define(function(require, exports, module) {
    "use strict";
    var $ = require("$"),
        app = require("dist/application/app"),
        config = app.config,
        method = app.method;
    require("wookmark");
    var articleItem = require("./items/articleItem.html");
    var videoBlockTpl = require("./blocks/videoBlockTpl.html");


    var render_list = template.compile(videoBlockTpl);
    var render_item = template.compile(articleItem);

    var composeArticleView = require('./composes/composeArticleView.html');
    var articleView = require("./preview/articleView.html");
    var articlefooter = require("./footers/articlefooter.html")


    var articleView1 = require("./preview/articleView1.html");
    var articleView2 = require("./preview/articleView2.html");
    var articleView3 = require("./preview/articleView3.html");


    var emptyHtml = require('./emptys/graphic.html')
    var articlefiles = function(element, layout) {
        this.element = $(element);
        this.layout = layout;
        this.selector = ".js_article_container .video_unit:last";
        this.type = window.message_config.files_type_ids[4];
        this.init();
    }
    articlefiles.prototype.init = function() {
        this.element.empty();
        this.events();
        this.selectView();
        this.fileModel = {
            FileID: 0,
            MpNews: {},
            multiple: false
        };
        this.article = {
            author: "",
            content: "",
            content_source_url: "",
            digest: "",
            title: "",
            thumb_path: "",
            file_name: '',
            file_id: 0,
            show_thumb_in_content: 0
        };
        this.narticle = {
            author: "",
            content: "",
            content_source_url: "",
            digest: "",
            title: "",
            thumb_path: "",
            file_name: '',
            file_id: 0,
            show_thumb_in_content: 0
        };
        this.selected = 0; //当前选择图文
        this.model = {}
    };
    articlefiles.prototype.templateData = function() {
        var article = this.fileModel.MpNews.articles ? $.extend({}, this.article, this.fileModel.MpNews.articles[this.selected]) : this.article;
        return $.extend({}, article, this.fileModel, {
            model: this.model
        });
    };
    articlefiles.prototype.selectData = function(data) {
        var _self = this;
        $(".js_add_message").off("click").removeAttr('disabled').bind('click', function(event) {
            _self.generate(data)
        });
    }
    articlefiles.prototype.events = function() {
        var _self = this;
        $(document).off('click.js_article_container').on("click.js_article_container", ".js_article_container .video_unit", function() {
            var $this = $(this),
                $fileId = $this.closest('li').data("fileId");
            $(".js_article_container .video_unit").removeClass('selected');
            $this.addClass('selected').siblings().removeClass('selected');
            $fileId && _self.selectData(window.files[_self.type][$fileId]);

        })

    };
    articlefiles.prototype.validation = function() {

        for (var i = this.fileModel.MpNews.articles.length - 1; i >= 0; i--) {
            var nb = i + 1;
            var article = this.fileModel.MpNews.articles[i]
            if ($.trim(article.title).length == 0) {
                config.msg.info("请输入图文{0}的标题".format(nb))
                return false;
            };
            if ($.trim(article.thumb_path).length == 0) {
                config.msg.info("请输入图文{0}的封面图片".format(nb))
                return false;
            };
            if ($.trim(article.content).length == 0) {
                config.msg.info("请输入图文{0}的正文".format(nb))
                return false;
            };
        };
        return true;
    };
    articlefiles.prototype.sync = function($warp) {

        var _self = this;
        var article = this.fileModel.MpNews.articles[this.selected];
        var $inputs = $('.js_message_edition_wrap input[type="text"],textarea[name="content"],.js_message_edition_wrap input[type="checkbox"]');
        var inputdata = {}
        $.each($inputs, function(index, val) {
            var $this = $(this);
            if ($this.attr("type") == "checkbox") {
                inputdata[$this.attr("name")] = $this.prop('checked')?1:0;
            } else {
                inputdata[$this.attr("name")] = $this.val()
            }

        });
        this.article = this.fileModel.MpNews.articles[this.selected] = $.extend({}, article, inputdata);
        var preview = template.compile(articleView)(this.templateData());
        this.layout.setPreview(preview);
        this.previewItems($(preview))
        this.selectedArticle()

    }
    articlefiles.prototype.generateChange = function($warp) {
        var _self = this;
        $(".js_article_title,.js_article_digest,.js_article_author,js_article_content_source_url", $warp).on("keyup", function() {
            _self.sync();
        })
        $(".js_show_thumb_in_content", $warp).on("click", function() {
            // this.fileModel.show_thumb_in_content = $(this).prop('checked');
            _self.sync();
        })
        // .on("blur", function() {
        //     _self.sync();
        // })
        $(".group_item_close", $warp).on("click", function() {
            $(".js_upload_complete").hide();
            _self.article.thumb_path = config.empty;
            _self.sync();
        })
        $(".js_upload", $warp).uploader({
            url: window.message_config.upload_path,
            data: {
                type: _self.type,
                data: window.message_config.upload_params,
                FileID: _self.fileModel.FileID,
                multiple: _self.fileModel.multiple
            },
            FilesAdded: function(up, files) {
                $(".js_upload_complete").hide();
                $(".js_upload_progress").show();
                var file = files[0];
                $(".video_upload_filename").html("{0} ({1})".format(file.name, plupload.formatSize(file.size)))
            },
            UploadProgress: function(up, file) {
                var percent = file.percent + "%";
                $(".js_process").width(percent)

            },
            FileUploaded: function(up, file, res) {
                if ($.isPlainObject(res)) {
                    _self.article.thumb_path = res.Image.thumb_path;
                    _self.article.file_id = res.file_id;
                    _self.article.file_name = "{0} ({1})".format(res.file_name, res.size);

                } else {
                    up.files.removeFile(file);
                    config.msg.info(res || config.lang.uplodError);
                }
            },
            UploadComplete: function(up, files) {
                _self.generate(_self.templateData());
            }
        }, "picture")

    }
    articlefiles.prototype.selectView = function() {
        var $footer = $(articlefooter);
        var _self = this;
        var list_data = {};
        $(".js_new_message", $footer).on("click", function() {
            var type = $(this).data("type");
            _self.fileModel.multiple = (type == 'more')
            _self.generate();
        })
        this.layout.setFooter($footer);
    }
    articlefiles.prototype.previewItems = function() {
        var _self = this,
            $list = $(".js_list");
        if (this.fileModel.MpNews.articles) {
            if (this.fileModel.multiple) {
                $.each(this.fileModel.MpNews.articles, function(index, item) {
                    if (index == 0) {
                        $list.append(template.compile(articleView2)(item))
                    } else {
                        $list.append(template.compile(articleView3)(item))
                    }
                });
            } else {
                $.each(this.fileModel.MpNews.articles, function(index, item) {
                    $list.append(template.compile(articleView1)(item))
                });
            }

        };

    }
    articlefiles.prototype.selectedLastArticle = function() {
        var $this_art = $($(".js_article")[this.fileModel.MpNews.articles.length - 1]);
        $this_art.addClass('active').siblings().removeClass('active delete');
        this.fileModel.MpNews.articles.length > 0 && $this_art.addClass('delete');
        this.article = this.fileModel.MpNews.articles[this.selected];
    }
    articlefiles.prototype.selectedArticle = function() {
        var $this_art = $($(".js_article")[this.selected]);
        $this_art.addClass('active').siblings().removeClass('active delete');
        this.fileModel.MpNews.articles.length > 0 && $this_art.addClass('delete');

    }
    articlefiles.prototype.generateInit = function() {
        var _self = this;
        var updateEd = function() {
            require.async(["kindeditor"], function() {
                var $ed = $(".js_article_content")
                var Kconfig = $.extend({}, config.kindeditor["simple"], {
                    afterChange: function() {
                        _self.sync()
                    }
                });
                KindEditor.create($ed, Kconfig);
            })

        };
        updateEd()


        var updateWarp = function() {
            var warp = template.compile(composeArticleView)(_self.templateData());
            var $warp = $(warp);
            _self.generateChange($warp);
            _self.layout.setWarp($warp);
            updateEd()

        }
        $(document).off('click.video_unit').on("click.video_unit", ".js_append", function() {
            if (_self.fileModel.MpNews.articles.length > 9) {
                config.msg.info("最多添加9个图文");
                return false;
            };
            _self.fileModel.MpNews.articles.push(_self.narticle);
            _self.sync();
            _self.selected = _self.fileModel.MpNews.articles.length - 1;
            updateWarp()
            _self.selectedLastArticle();

        });
        $(document).off('click.js_list').on("click.js_list", ".js_article", function() {
            var index = $(".js_article").index(this);
            $(this).addClass('active').siblings().removeClass('active delete')
            _self.selected = index;
            index > 0 && ($(this).addClass('delete'))
            updateWarp()
        });
        $(document).off('click.js_article').on("click.js_article", ".js_delete ", function() {
            var $this = $(this),
                $article = $this.closest('.js_article');
            var index = $(".js_article").index($article);
            _self.fileModel.MpNews.articles.removeAt(index);
            _self.selected = index;
            $article.remove();
            _self.selectedLastArticle();

        });

    }
    articlefiles.prototype.generate = function(data) {
        var _self = this;
        if (data) {
            this.fileModel.FileID = data.file_id;
            this.fileModel.MpNews = data.MpNews;
            if (!this.fileModel.multiple) {
                this.fileModel.multiple = data.MpNews.articles.length >= 2
            };

            if (!this.article.file_name) {
                var selectedArticle = this.fileModel.MpNews.articles[this.selected];
                this.article.file_name = selectedArticle.thumb_path.substr(selectedArticle.thumb_path.lastIndexOf('/') + 1)
            };


        } else {
            if (!this.fileModel.MpNews.articles) {
                this.fileModel.MpNews.articles = [];
                this.fileModel.MpNews.articles.push(this.article);
            };
        }
        var warp = template.compile(composeArticleView)(this.templateData());
        var $warp = $(warp);

        var preview = template.compile(articleView)(this.templateData());

        this.generateChange($warp);
        this.layout.setWarp($warp);
        this.layout.showPreview();
        this.layout.setPreview(preview);
        this.previewItems($(preview))
        this.selectedArticle()
        this.layout.setMassfooter(this);
        this.generateInit();
        this.layout.blcokDestroy()
    }
    articlefiles.prototype.list = function(data) {

        var sp = $('ul:last', this.element);
        if (sp.length) {
            sp.append(render_item({
                list: data.file_item
            }))
        } else {
            if (data.last_file_item.length) {
                this.element.append(render_list({
                    file_items: render_item({
                        list: data.file_item
                    })
                }));
            } else {
                this.element.html(emptyHtml)
            }
        }
        $(".js_video_container li.tile").wookmark({
            align: "left",
            autoResize: !0,
            direction: 'left',
            container: $(".js_article_container .js_items"),
            offset: 0
        })
    };

    return articlefiles;

})
